<template>
  <div class="permission">
    <div class="operate">
<!--        <div style="flex: 0 0 auto">
          <ep-search
              v-model="queryParam.b0102"
              placeholder="请输入点位名称"
              enter-button="chaxun "
              @search="
              () => {
                this.listQuery();
              }
            "
          ></ep-search>
        </div>-->
      <ep-button
          style="margin-left: 15px;float: right"
          @click="
            () => {
              this.handleCancelTwo();
            }
          "
      >返回</ep-button
      >


      <div style="float: right">
<!--        <ep-button-->
<!--            @click="-->
<!--            () => {-->
<!--              this.editPatrolSet();-->
<!--            }-->
<!--          "-->
<!--        >编辑</ep-button
        >-->

        <ep-button
            v-if="buttonShow"
            @click="
            () => {
              this.addPoint();
            }
          "
        >新增点位</ep-button>

        <ep-button
            v-if="buttonShow"
            style="margin-left: 10px;"
            @click="
            () => {
              this.delPoint();
            }
          "
        >删除点位</ep-button>

        <ep-button
            style="margin-left: 10px;"
            icon="export.svg"
            @click="
            () => {
              this.exportExcel();
            }
          "
        >导出</ep-button
        >
      </div>


    </div>
    <div class="ep-table">
      <zh-table
          ref="tableList"
          rowId="roleId"
          :url = "tableUrl"
          :columns="tableColumn"
          :data="tableData"
          @checkbox-change="selectChangeEvent"
          @checkbox-all="selectAllEvent"
          @page-change="PageChangeEvent"
          size="medium"
          height="520px"
      >
        <template #filter="{ $panel, column }">
          <input
              type="type"
              v-for="(option, index) in column.filters"
              :key="index"
              v-model="option.data"
              @input="$panel.changeOption($event, true, option)"
          />
        </template>
      </zh-table>
    </div>
    <a-modal
        title="巡查设置"
        centered
        style="top: 20px"
        width="55%"
        height="100%"
        destroyOnClose
        v-model="visible"
        cancelText="关闭"
        @ok="handleOk"
        @cancel="handleCancel"
    >
      <patrol-set-details-form
          ref="patrolSetDetailsForm"
          @handleCancel="handleCancel"
          @handleCancelTwo="handleCancelTwo"
          @showOrHide="showOrHide"
          :set-patrol-data-two="patrolDataChange">
      </patrol-set-details-form>
      <template slot="footer">
        <ep-button @click="handleOk" >确认</ep-button>
        <ep-button @click="handleCancel">取消</ep-button>
      </template>
    </a-modal>

    <a-modal
        title="新增点位"
        centered
        style="top: 20px"
        width="35%"
        height="100%"
        destroyOnClose
        v-model="visible2"
        cancelText="关闭"
        @ok="handleOk2"
        @cancel="handleCancel2"
    >
      <zh-form  ref="formInfo"  :model="formInfo"  labelAlign="right" >
        <zh-card style="width:100%">
          <zh-row>
            <zh-input
                prop="b0122"
                type="select"
                :span="20"
                label="行政区划"
                :options="XZQH"
                v-model="formInfo.b0122"
            ></zh-input>
            <zh-input label="点位名称" show-search :labelInValue="true" :filter-option="false"
                      :not-found-content="fetching ? undefined : null" :span="20"
                      :defaultFields="{label: 'b0102',value: 'b0101'}" type="select" placeholder="请输入点位名称"
                      v-model="b01"
                      :options="b01DataList"
                      @search="handleSearch"
                      @change="handleChange">
              <a-spin v-if="fetching" slot="notFoundContent" size="small"/>
            </zh-input>
          </zh-row>
        </zh-card>
      </zh-form>
      <template slot="footer">
        <ep-button @click="handleOk2" >确认</ep-button>
        <ep-button @click="handleCancel2">取消</ep-button>
      </template>
    </a-modal>

  </div>
</template>

<script>
import {getBatchDict,getDictCondition} from "@/services/system/api"
import {getB01DataList,addPatrolPoint} from '@/services/system/whdngxlApi'
import UnmovableRelics from "@/pages/whdngxl/TasksCheckManage/UnmovableRelics";
import patrolSetDetailsForm from "@/pages/system/form/PatrolSetDetailsForm";
import modal from "ant-design-vue/es/modal";

let timeout;
let currentValue;
export default {
  components:{
    patrolSetDetailsForm
  },
  props:{
    resourcesChange:{
      type:Function,
      default:null
    }
  },
  data() {
    return {
      filtersData: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 分页参数
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 200,
      },
      queryParam:{
        manageAreas:undefined,
        c0303:'',
        d0201:'',
        b0102:'',
      },
      rules:{},
      dictData: {
        c0303:[],
      },
      loading: false,
      selectedRowKeys: [] /*table选中keys*/,
      selectionRows: [] /*table选中records*/,
      tableUrl: '',
      tableData: [],
      taskData:[],
      tableColumn: [
        { type: "checkbox", width: 50, fixed: "left", visible: true },
        {
          type: "seq",
          width: 80,
          fixed: "left",
          align: "center",
          title: "序号",
          visible: true,
        },
        {
          field: "b0101",
          title: "点位ID",
          visible: false,
          align: "center",
          width: 150,
        },
        {
          field: "d0401",
          title: "巡查任务信息表ID",
          visible: false,
          align: "center",
          width: 150,
        },
        {
          field: "b0103",
          title: "编号",
          align: "center",
          width: 100,
          visible: true,
        },
        {
          field: "b0102",
          title: "名称",
          align: "center",
          width: 150,
          visible: true,
        },
        {
          field: "b0129Name",
          title: "巡查级别",
          align: "center",
          filters: [],
          width: 150,
          visible: true,
        },
        {
          field: "b0104Name",
          title: "古系列类别",
          align: "center",
          filters: [],
          width: 150,
          visible: true,
        },
        {
          field: "b0105Name",
          title: "文保级别",
          align: "center",
          filters: [],
          width: 150,
          visible: true,
        },
        {
          field: "patrolMan",
          title: "巡查人",
          align: "center",
          fixed: "right",
          width: 150,
          visible: true,
          filters: [{ data: "" }],
          filterMethod: this.filterPatrolManMethod,
          slots: {
            // 使用插槽模板渲染
            filter: "filter",
          },
        },
        {
          field: "b0106Name",
          title: "时代",
          align: "center",
          filters: [],
          width: 150,
          visible: true,
        },
        {
          field: "b0122",
          title: "县区编码",
          visible: false,
          align: "center",
          width: 150,
        },
        {
          field: "b0123",
          title: "街道编码",
          visible: false,
          align: "center",
          width: 150,
        },
        {
          field: "manageArea",
          title: "管理区域",
          align: "center",
          width: 250,
          visible: true,
        },
        {
          field: "b0113Name",
          title: "是否核销",
          align: "center",
          filters: [],
          width: 120,
          visible: true,
        },
        {
          field: "b0114Name",
          title: "是否安全",
          align: "center",
          filters: [],
          width: 120,
          visible: true,
        },
        {
          field: "b0115Name",
          title: "是否划定保护双线",
          align: "center",
          filters: [],
          width: 180,
          visible: true,
        },
        {
          field: "b0109",
          title: "地址",
          align: "center",
          width: 200,
          visible: true,
        },
        {
          field: "b0117Name",
          title: "省级文保类别",
          align: "center",
          filters: [],
          width: 150,
          visible: true,
        },
        {
          field: "b0118Name",
          title: "省级文保子类",
          align: "center",
          filters: [],
          width: 150,
          visible: true,
        },
        {
          field: "b0121",
          title: "开放时间",
          sortable: true,
          align: "center",
          width: 120,
          visible: true,
        },
      ],
      visible: false,
      visible2:false,
      formInfo:{},
      fetching: false,
      b01DataList: [],
      b01: undefined,
      buttonShow:true, //相关按钮是否显示
      XZQH:{}
    }
  },

  created() {

  },
  methods: {
    initData(data){
      if(!data.d0201){
        this.buttonShow = false
      }
      const param = {}
      param.dictFields = 'c0303,b0104,b0105,b0106,b0113,b0114,b0115,b0117,b0118,b0129'
      this.$http.post(getBatchDict, param).then(res => {
        this.dictData = res.result
        //获取筛选数据
        UnmovableRelics.methods.getFiltersData(this, "tableList");
      })

      const params = {}
      params.dictField = 'XZQH';
      params.dictKeys = data.taskArea.join(',');
      this.$http.post(getDictCondition,params).then(res =>{
        this.XZQH = res.result;
      })
      this.selectionRows = []
      this.queryParam = data
      this.tableData = data.resourcesData
    },
  /*  editPatrolPoint(){
      //判断巡查点是否已经有对应的巡查任务
      const params = Object.assign(this.taskData)
      /!*if (this.$refs.tableList.isAllChecked) {
        this.selectionRows = this.$refs.tableList.getCheckboxRecords();
      } else {
        this.selectionRows = this.$refs.tableList.getAllCheckboxRecords();
      }*!/
      params.resourcesData = this.selectionRows
      setTimeout(() => {
        this.$http
            .post(checkPointRepeat, params)
            .then((res) => {
              if(this.resourcesChange){
                this.resourcesChange(this.selectionRows)
              }
              this.handleCancel()
            })
            .catch((error) => {
              console.log(JSON.stringify(error));
            })
            .finally(() => {});
      }, 50);
    },
    //根据父页面传进来的文物资源回显勾选的数据,入参是分页查询的table数据
    echoResourcesData(data) {
      const that = this
      let resourcesData = this.taskData.resourcesData
      if (resourcesData.length > 0) {
        const have = [];
        resourcesData.forEach(el => {
          have.push(el.b0101)
        })
        this.selectionRows = data.filter(function (e) {
          if (have.indexOf(e.b0101) !== -1) {
            // console.log("setCheckboxRow"+e.b0101)
            that.$refs.tableList.setCheckboxRow(e, true)
            that.$refs.tableList.count += 1
            return e
          }
        })
      }
    },*/
    handleSearch(value) {
      this.fetch(value, data => (this.b01DataList = data));
    },
    fetch(value, callback) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      currentValue = value;
      function fake(that) {
        that.fetching = true
        if (value) {
          that.$http.post(getB01DataList, {b0102: value, b0122: that.formInfo.b0122}).then(res => {
            console.log(res)
            callback(res.result);
          }).catch((error) => {
            console.log(JSON.stringify(error))
          }).finally(() => {
            that.fetching = false
          })
        }
      }
      timeout = setTimeout(fake(this), 300);
    },
    handleChange(option) {
      this.b01 = option
    },
    //添加点位
    addPoint(){
      this.visible2 = true;
      this.formInfo.b0122 = this.queryParam.taskArea[0]
    },
    //删除点位
    delPoint(){
        if (this.$refs.tableList.isAllChecked) {
          this.selectionRows = this.$refs.tableList.getCheckboxRecords();
        } else {
          this.selectionRows = this.$refs.tableList.getAllCheckboxRecords();
        }
        if (this.selectionRows.length === 0) {
          modal.warn({ title: "提示", content: "请至少选择一条数据" });
          return;
        }
        let beforeChooseCount = this.tableData.length;
        modal.confirm({
          title: "确认删除吗？",
          onOk: () => {
            this.selectionRows.forEach(record => {
              this.tableData = this.tableData.filter(item => item.b0101 !== record.b0101);
            });
            // 触发事件，将修改后的数据发送给父组件
            this.$emit('updatePatrolSetData', this.tableData.length, this.tableData , beforeChooseCount);
          },
          onCancel: () => {},
        });
    },
    handleOk2() {
      if(this.b01 == undefined){
        modal.warn({title: '提示', content: '点位名称不能为空'})
        return
      }
      let beforeChooseCount = this.tableData.length;
      const params = {}
      params.b0101 = this.b01.key
      params.b0102 = this.b01.label
      params.d0201 = this.queryParam.d0201
      params.d0706 = this.queryParam.d0706
      setTimeout(() => {
        this.$http.post(addPatrolPoint, params).then((res) => {
          // 将新记录添加到 tableData 列表中
          this.tableData.push(res.result.resourcesData[0]);
          // 触发事件，将修改后的数据发送给父组件
          this.$emit('updatePatrolSetData', this.tableData.length, this.tableData , beforeChooseCount);
          this.$message.info("新增成功");
          this.visible2 = false
        }).catch((error) => {
          console.log(JSON.stringify(error))
        }).finally(() =>{
        })
      }, 50)

    },
    handleCancel2() {
      this.visible2 = false;
    },
    exportExcel(){

    },
    editPatrolSet(){
      this.visible = true;
      this.$nextTick(() => {
        if (this.queryParam.d0201) {
          this.queryParam.flag = "edit";
        }
        this.$refs.patrolSetDetailsForm.initData(this.queryParam,true);
      });
    },
    patrolDataChange(data){
      if(this.resourcesChange){
        this.resourcesChange(data)
      }
    },
    handleCancel() {
      this.visible = false;
    },
    //从该页面编辑巡查设置的话，保存完之后需要直接关闭两层子页面
    handleCancelTwo(){
      this.visible = false;
      this.$emit("handleCancel")
    },
    showOrHide() {
      this.visible = !this.visible;
    },
    handleOk() {
      this.$nextTick(() => {
        this.$refs.patrolSetDetailsForm.confirm();
      });
    },
    PageChangeEvent(vim){
      // this.echoResourcesData(vim.tableData)
    },
    //复选框事件(保留翻页选中的数据)
    selectChangeEvent({ checked, records, reserves, row }) {
      // console.log(checked ? '勾选事件' : '取消事件')
      // console.log('当前选中的数据：' + records)
      // console.log('翻页时其他页的数据：' + reserves)
      // console.log('当前选中的数据行：' + row )
      //勾选选中时
      if (checked) {
        //第一次选数据，还未进行翻页时
        if (reserves.length == 0) {
          this.selectedRowKeys = records.map((v) => v.b0101);
          this.selectionRows = records;
        } else {
          //b0101集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectedRowKeys = [
            ...reserves.map((v) => v.b0101),
            ...records.map((v) => v.b0101),
          ];
          //数据集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectionRows = [...reserves, ...records];
        }
      } else {
        //取消选中时
        let b0101Index = this.selectedRowKeys.indexOf(row.b0101);
        if (b0101Index > -1) {
          //删除取消选中删除指定元素b0101
          this.$delete(this.selectedRowKeys, b0101Index);
        }

        let dataIndex = null;
        for (let i = 0; i < this.selectionRows.length; i++) {
          if (this.selectionRows[i].b0101 == row.b0101) {
            dataIndex = i;
            break;
          }
        }
        //删除取消选中的元素整个对象
        this.$delete(this.selectionRows, dataIndex);
      }
    },
    //vxe复选框当前页全选中方法(保留翻页选中的数据)：
    selectAllEvent({ checked, records, reserves }) {
      // console.log(checked ? '勾选事件' : '取消事件')
      // console.log('当前选中的数据：' + records)
      // console.log('翻页时其他页的数据：' + reserves)
      //全选中时
      if (checked) {
        //第一次选数据，还未进行翻页时
        if (reserves.length == 0) {
          this.selectedRowKeys = records.map((v) => v.b0101);
          this.selectionRows = records;
        } else {
          //b0101集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectedRowKeys = [
            ...reserves.map((v) => v.b0101),
            ...records.map((v) => v.b0101),
          ];
          //数据集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectionRows = [...reserves, ...records];
        }
      } else {
        //取消全选时,直接将翻页数据赋值，当前页数据不用加上
        this.selectionRows = reserves;
        this.selectedRowKeys = reserves.map((v) => v.b0101);
      }
    },
    filterPatrolManMethod({ option, row }) {
      return row.patrolMan.includes(option.data);
    },
  }
}
</script>
<style lang="less" scoped>
.permission {
  //padding: 15px 20px 0;
  height: 100%;

  .desc,
  .operate {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;

    > div {
      flex: 0 0 auto;
      display: flex;
      align-items: center;
    }
  }

  .desc {
    margin-bottom: 20px;
  }

  .operate {
    margin-bottom: 15px;
    .field {
      flex: 0 0 auto;
      position: relative;
      margin-left: 15px;
      .field-box {
        position: absolute;
        top: 40px;
        left: 0;
        right: -40px;
        z-index: 99;
        border: 1px solid #2175a9;
        background: #002a44;
        border-radius: 5px;
        ul {
          padding: 10px;
          li {
            padding: 1px 0;
          }
        }
        .btn {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 5px;
          border-top: 1px solid #2175a9;
          color: #fff;
          p {
            flex: 1;
            text-align: center;
            cursor: pointer;
            &:hover {
              color: #49bbeb;
            }
          }
        }
      }
    }
  }
  .ep-table {
    height: calc(100% - 130px);
  }
}
</style>